<?php
namespace backend\models;
use Yii;
use yii\db\ActiveRecord;
use yii\helpers\ArrayHelper;

class Category extends ActiveRecord{

    public static function tableName(){
        return "{{%category}}";
    }

    public function rules(){
        return [
            ['parentid', 'required', 'message' => '上级分类不能为空'],
            ['title', 'required', 'message' => '标题不能为空'],
            /*['title', 'unique', 'message' => '此名称已经被占用'],*/
            ['path', 'required', 'message' => '路径不能为空'],
            ['create_time', 'safe'],
        ];
    }

    public function attributeLabels(){
        return [
            'parentid' => '上级分类',
            'title' => '分类名称',
            'path' => '路径'
        ];
    }

    public function addCate($data){
        if($this->load($data) && $this->validate()){
           return  $this->save();
        }
        return false;
    }

    public function getData(){
        $cates = self::find()->all();
        $cates = ArrayHelper::toArray($cates);
        return $cates;
    }

    public function getTree($cates, $pid = 0){
        $tree = [];
        foreach($cates as $cate){
            if($cate['parentid'] == $pid){
                $tree[] = $cate;
                $tree = array_merge($tree, $this->getTree($cates, $cate['cateid']));
            }
        }
        return $tree;
    }

    public function setPrefix($data, $p = '|----'){
        $tree = [];
        $num = 1;
        $prefix = [0 => 1];
        while($var = current($data)){
            $key = key($data);
            if($key>0){
                if($data[$key - 1]['parentid'] != $var['parentid']){
                    $num++;
                }
            }
            if(array_key_exists($var['parentid'], $prefix)){
                $num = $prefix[$var['parentid']];
            }
            $var['title'] = str_repeat($p, $num) . $var['title'];
            $prefix[$var['parentid']] = $num;
            $tree[] = $var;
            next($data);
        }
        return $tree;
    }

    public function getOptions(){
        $data = $this->getData();
        $tree = $this->getTree($data);
        $tree = $this->setPrefix($tree);
        $options = ['添加顶级分类'];
        foreach($tree as $cate){
            $options[$cate['cateid']] = $cate['title'];
        }
        return $options;
    }

    public function getTreeList(){
        $data = $this->getData();
        $tree = $this->getTree($data);
        return $tree = $this->setPrefix($tree);

    }
}
